import { Select } from 'antd';
import React from 'react';
import axios from 'axios';
import { connect } from 'react-redux';
import './index.css';

const { Option } = Select;

class SearchInput extends React.Component {
  state = {
    data: [],
    value: '',
    temp:[],
  };

  componentDidMount = ()=>{
    axios.post('http://localhost:8080/tsonglist/query',{
      param:{
        creator: this.props.id,
      }
    }).then((res)=>{
      this.setState({
        data: res.data.rows,
        temp: res.data.rows,
      })
    })
  }

  handleSearch = value => {
    if (value) {
      this.setState({
        temp: this.state.data?.filter((item,index)=>{
          return new RegExp(".*"+value+".*").test(item.name);
        })
      })
    } else {
      this.setState({ temp: this.state.data });
    }
  };

  handleChange = value => {
    this.props.getValue(value)
    this.setState({ value });
  };


  render() {
    const options = this.state?.temp?.map(d => <Option key={d.id}>{d.name}</Option>);
    return (
      <Select
        showSearch
        value={this.state.value}
        placeholder={this.props.placeholder}
        className='select'
        defaultActiveFirstOption={false}
        showArrow={false}
        filterOption={false}
        onSearch={this.handleSearch}
        onChange={this.handleChange}
        notFoundContent={'无歌单，请新建'}
      >
        {options}
      </Select>
    );
  }
}

const mapStateToProps = (state) => {
  return {
    id: state.id,
    username: state.username,
  }
}

export default connect(mapStateToProps)(SearchInput);